<?php

class categoryActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    /**
     * Ангилалын жагсаалт
     *
     * @param sfWebRequest $request
     */
    public function executeList(sfWebRequest $request) {
        $isActive = $request->getParameter('isActive', 0);
        $this->isActive = $isActive;
        $this->rows = CategoryTable::getList($isActive);
    }

    /**
     * Ангилал нэмэх/засах
     * 
     * @param sfWebRequest $request
     */
    public function executeUpdate(sfWebRequest $request) {
        $id = $request->getParameter('id');
        $user = $this->getUser();

        if ($id) {
            $category = CategoryTable::retrieveByPK($id);
            if (!$category) {
                $this->getUser()->setFlash('warning', 'Ангилал олдсонгүй');
                $this->redirect($request->getReferer());
            }
            $flash = 'Амжилттай заслаа';
        } else {
            $category = new Category();
            $flash = 'Амжилттай нэмлээ';
        }

        $form = new CategoryForm($category);

        if ($request->isMethod('post')) {
            $form->bind($request->getParameter('category'), $request->getFiles('category'));

            if ($form->isValid()) {
                $form->save();

                $this->getUser()->setFlash('success', $flash);
                $this->redirect('@category_list');
            }
        }

        $this->form = $form;
        $this->id = $id;
        $this->category = $category;
    }

    /**
     * Төлөв өөрчлөх
     * 
     * @param sfWebRequest $request
     */
    public function executeChangeState(sfWebRequest $request) {
        $category = CategoryTable::retrieveByPk($request->getParameter('id'));
        if ($category) {
            if ($category->is_active == CategoryTable::ACTIVE) {
                $category->setIsActive(CategoryTable::PASSIVE);
                $this->getUser()->setFlash('success', 'Амжилттай устгалаа');
            } elseif ($category->is_active == CategoryTable::PASSIVE) {
                $category->setIsActive(CategoryTable::ACTIVE);
                $this->getUser()->setFlash('success', 'Амжилттай сэргээлээ');
            }

            $category->save();
        } else {
            $this->getUser()->setFlash('error', 'Ангилал олдсонгүй!');
        }

        $this->redirect('@category_list');
    }

}
